<template>
  <div class="contrain">
    <HeadTitle :middle="true"
               :right="true">
      <template v-slot:middle>
        <h1>畅所欲言吧~</h1>
      </template>
      <template v-slot:right>
        <van-icon name="add-o"
                  @click="Issue" />
      </template>
    </HeadTitle>
    <van-pull-refresh v-model="Loading"
                      @refresh="onRefresh">
      <van-list v-model="loading"
                :finished="finished"
                finished-text="没有更多了"
                @load="onLoad"
                v-show="!isLoading">
        <div class="Invis">
          <div v-if="Invi.length === 0">
            <van-empty description="讨论区空空如也~来发表第一条帖子吧！" />
          </div>
          <div v-for="(item, i) in Invi"
               :key="i">
            <Invi :main=item
                  @click="goInvi(item._id)" />
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import Invi from '_c/Forum/Invitations.vue'
import HeadTitle from '_c/utils/HeadTitle.vue'
import { getInvi, RefreshInvi } from '@/api/forum'
export default {
  components: { Invi, HeadTitle },
  data () {
    return {
      Invi: [],
      loading: false,
      finished: false,
      page: 1,
      isLoading: true,
      Loading: false
    }
  },
  methods: {
    Issue () {
      this.$router.push('/CreateInvi')
    },
    fetch () {
      const toast = this.$toast.loading({
        duration: 0,
        forbidClick: true,
        message: '加载中'
      })
      getInvi(this.page).then(res => {
        this.Invi.push(...res.data)
        toast.clear()
        this.isLoading = !this.isLoading
      }).catch(() => {
        this.$toast.fail('服务器开小差啦~请刷新页面重试')
      })
    },
    onRefresh () {
      this.page = 1
      RefreshInvi().then(res => {
        this.Invi = res.data
        this.Loading = !this.Loading
      }).catch(() => {
        this.Loading = !this.Loading
      })
    },
    onLoad () {
      this.loading = true
      setTimeout(async () => {
        this.page++
        getInvi(this.page).then(res => {
          this.Invi.push(...res.data)
          if (res.data.length < 10) {
            this.finished = true
          }
        }).catch(() => {
          this.$toast.fail('服务器开小差啦~请刷新页面重试')
          this.finished = true
          this.loading = false
        }).then(() => {
          this.loading = false
        })
      }, 1000)
    }
  },
  created () {
    this.fetch()
  }
}
</script>

<style lang="less" scoped>
.contrain {
  .van-icon {
    font-size: 30px;
  }
  .Invis {
    padding: 0 10px;
    margin-top: 80px;
    div {
      margin-bottom: 10px;
    }
  }
}
</style>
